package elems;

import common.ParseException;
import common.Strings;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AnchorDefine {
    private Clazz parent;
    private String name;
    private String comment;
    private String params;
    private boolean isVirtyal;

    private AnchorDefine(Clazz parent, String name, String comment, String params) throws ParseException {
        this.parent=parent;
        this.name = name;
        this.comment = comment;
        this.params=params;
        this.isVirtyal =params!=null || !parent.isHasSelectors();
        //this.params = Strings.split(-1, params, ",", false, true);
        //for (int i = 0; i < this.params.size(); i++)
        //    this.params.set(i, this.params.get(i).trim());
    }

    public void print(int shift) {
        System.out.println(Strings.getSpaceShift(shift) + "@@" + name + "(какие-то параметры: "+params+") /* [ANCHOR DEFINE"+((isVirtyal)?" VIRTUAL":"")+"] " + comment + "*/");
    }

    public static boolean is(int lineNum, String text, String nextText) throws ParseException {
        return Anchor.is(lineNum, text) && Strings.getSpaceShift(text) < Strings.getSpaceShift(nextText);
    }

    public static AnchorDefine get(Clazz parent, int lineNum, String text, String nextText) throws ParseException {
        if(!is(lineNum,text,nextText))
            return null;
        ArrayList<String> ttt = Strings.split(lineNum, Strings.trimAndDelDoubleSpace(text), "//", true, true);
        String tText = Strings.replaceAll(ttt.get(0), " ", "");
        String tComment = (ttt.size() > 1) ? ttt.get(1).trim() : "";

        Pattern pattern = Pattern.compile("^@@[A-Za-z0-9_]+");
        Matcher matcher = pattern.matcher(tText);
        if (matcher.find()) {
            pattern = Pattern.compile("^@@[A-Za-z0-9_]+");
            matcher = pattern.matcher(tText);
            matcher.find();
            String name = matcher.group().substring(2);
            pattern = Pattern.compile("\\(.*\\)");
            matcher = pattern.matcher(tText);
            String params=null;
            if (matcher.find()) {
                params = matcher.group();
                params = params.substring(1, params.length() - 1);
            }
            return new AnchorDefine(parent, name, tComment, params);
        }
        return null;
    }
}
